<template>
  <el-drawer
    :visible.sync="visible"
    direction="rtl"
    size="60%"
    :close-on-press-escape="false"
    :wrapper-closable="false"
    :show-close="false"
  >
    <template v-slot:title>
      <div class="drawer-header">
        <span>枚举</span>
        <div>
          <el-button icon="el-icon-close" @click="handleClose">
            取消
          </el-button>
        </div>
      </div>
    </template>
    <div class="app-container">
      <!-- 条件搜索 -->
      <div class="filter-container">
        <el-input v-model="listQuery.param.text" placeholder="枚举描述" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 110px" class="filter-item" @change="handleFilterQuery">
          <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
        </el-select>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </div>
      <div class="filter-container">
        <div style="float: left;">
          <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
            新增
          </el-button>
        </div>
        <div style="float: right;">
          <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :key="tableKey"
        v-loading="loading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        scrollbar-always-on="true"
      >
        <el-table-column type="selection" width="50px" align="center" />
        <el-table-column label="序号" type="index" width="50px" align="center" />
        <el-table-column label="枚举描述" min-width="70px" align="left">
          <template v-slot="{row}">
            <span>{{ row.text }}</span>
          </template>
        </el-table-column>
        <el-table-column label="枚举键值" min-width="70px" align="left">
          <template v-slot="{row}">
            <span>{{ row.code }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用状态" class-name="status-col" width="70px">
          <template v-slot="{row}">
            <el-switch :value="row.status ==='Y'" disabled />
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="80px" align="left">
          <template v-slot="{row}">
            <span>{{ row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" min-width="60px" align="left">
          <template v-slot="{row}">
            <span>{{ row.updatedBy }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="160px" align="left">
          <template v-slot="{row}">
            <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
          <template v-slot="{row,$index}">
            <el-button v-permission="permission.edit" size="mini" type="warning" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
            <el-button v-permission="permission.del" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row,$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格分页 -->
      <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

      <!--枚举编辑组件页面-->
      <dict-data-edit ref="dictDataEdit" :dict-edit-params="dictEdit" />

    </div>
  </el-drawer>
</template>

<script>
import { getPageList, handleDelete } from '@/views/sys/dict/dict-code'
import permission from '@/directive/permission/index' // 权限判断指令
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import DictDataEdit from './data-edit.vue'

export default {
  // 当前页面名称（组件）
  name: 'DictData',
  // 引用的组件
  components: { Pagination, DictDataEdit },
  // 指令
  directives: { permission, waves },
  filters: {},
  // props属性
  props: {
    dictDataParams: {
      type: Object,
      require: true,
      default: undefined
    }
  },
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // 列表查询参数对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        param: {
          dictType: undefined,
          text: undefined,
          status: undefined
        }
      },
      // 状态字典
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层（这里这个变量创建一个新的，因为props是单向传输数据，而弹出层关闭时会修改visible的值）
      visible: false,
      // 弹出层状态
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增'
      },
      // 权限标识
      permission: {
        add: ['sys:dict:data:add'],
        edit: ['sys:dict:data:edit'],
        del: ['sys:dict:data:del']
      },
      // 表单校验规则
      rules: {
        text: [{ required: true, message: '枚举描述不能为空', trigger: 'change' }],
        code: [{ required: true, message: '枚举键值不能为空', trigger: 'change' }]
      },
      // 子组件数据对象
      dictEdit: {
        state: undefined,
        visible: false,
        formData: {
          id: undefined,
          code: undefined,
          text: undefined,
          dictType: this.dictDataParams.dictType,
          status: 'Y',
          remark: ''
        }
      }
    }
  },
  computed: {},
  watch: {
    // type: {
    //   handler(data) {
    //     this.listQuery.param.dictType = data
    //     this.dictType = data
    //   },
    //   deep: true
    // },
    // visible: {
    //   handler(data) {
    //     this.visible = data
    //   },
    //   deep: true
    // }
  },
  created() {},
  mounted() {},
  methods: {
    // 用于初始化参数
    init() {
      this.visible = this.dictDataParams.visible
      this.listQuery.param.dictType = this.dictDataParams.dictType
    },
    handleInit() {
      this.init()
      this.loading = true
      getPageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.listQuery.param.text = undefined
      this.listQuery.param.status = undefined
    },
    // 重置表单
    handleRestFormData() {
      this.dictEdit.formData = {
        id: undefined,
        code: undefined,
        text: undefined,
        dictType: this.dictDataParams.dictType,
        status: 'Y',
        remark: ''
      }
    },
    // 新增
    handleCreate() {
      this.handleRestFormData()
      this.dictEdit.formData.dictType = this.dictDataParams.dictType
      this.dictEdit.state = 'create'
      this.dictEdit.visible = true
      // 由于子组件是异步的，所以需要调用nextTick
      this.$nextTick(() => {
        // 调用子组件的方法
        this.$refs['dictDataEdit'].init()
      })
    },
    // 修改
    handleUpdate(row) {
      this.handleRestFormData()
      // 创建一个新的对象赋值
      this.dictEdit.formData = Object.assign({}, row)
      // 清理没有用的属性，避免数据不对问题
      delete this.dictEdit.formData.createdBy
      delete this.dictEdit.formData.createdTime
      delete this.dictEdit.formData.updatedBy
      delete this.dictEdit.formData.updatedTime
      delete this.dictEdit.formData.tenantId
      delete this.dictEdit.formData.revision
      delete this.dictEdit.formData.deleted

      this.dictEdit.state = 'update'
      this.dictEdit.visible = true
      // 由于子组件是异步的，所以需要调用nextTick
      this.$nextTick(() => {
        // 调用子组件的方法
        this.$refs['dictDataEdit'].init()
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ id: row.id }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 关闭弹出层
    handleClose() {
      this.visible = false
      // 这里要刷新父页面的列表
      this.$parent.handleFilterQuery()
    }
  }
}
</script>
